package org.yi.web.index;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yi.core.annotation.Action;
import org.yi.core.common.Constants;
import org.yi.core.enums.BlockTargetEnum;
import org.yi.core.render.YiCaptchaRender;
import org.yi.web.base.BaseController;
import org.yi.web.category.entity.CategoryEntity;
import org.yi.web.post.entity.PostEntity;

import com.jfinal.core.Const;

@Action(action = "/")
public class IndexController extends BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(IndexController.class);
	
	public void index() {
		try {
			setHeader();
			
			// get all bottom category
			List<CategoryEntity> allSub = CategoryEntity.dao.getAllSub();
			setAttr("subList", allSub);
			Map<String, List<PostEntity>> subCatPostList = new HashMap<String, List<PostEntity>>();
			for(CategoryEntity c : allSub) {
				subCatPostList.put("list_"+c.get("id"), PostEntity.dao.getByCategory(c));
			}
			setAttr("subCatPostList", subCatPostList);
			
			loadBlocks(BlockTargetEnum.INDEX);
			
			setAttr("recentReply", getRecentReply());
			
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		render("/themes/"+getSite().get("theme")+"/index.html");
	}
	
	public void login() {
		forwardAction("/user/login");
	}

	/**
	 * generate verify code
	 */
	public void captcha(){
		YiCaptchaRender captchRender = new YiCaptchaRender();
		render(captchRender);
	}
	
	/**
	 * used for i18n
	 */
	public void setLocal()  {
		String local = getPara(Constants.COOKIE_LOCAL);
		// set default local: CHINA if empty
		local = StringUtils.isBlank(local) ? Locale.CHINA.toString() : local;
		setCookie("Constants.COOKIE_LOCAL", local, Const.DEFAULT_I18N_MAX_AGE_OF_COOKIE);
		renderNull();
	}
	
	public void about() {
		setHeader();
		loadBlocks(BlockTargetEnum.ALL);
		render("/themes/"+getSite().get("theme")+"/about.html");
	}
	
	public void contact(){
		setHeader();
		loadBlocks(BlockTargetEnum.ALL);
		render("/themes/"+getSite().get("theme")+"/contact.html");
	}
	
	public void mianze() {
		setHeader();
		loadBlocks(BlockTargetEnum.ALL);
		render("/themes/"+getSite().get("theme")+"/mianze.html");
	}
	
}
